package cn.neo.support.recyclerview.material;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;

import cn.neo.support.R;
import cn.neo.support.utils.ScreenUtil;

/**
 * Name:自定义刷新
 * Author: WK（wangkun@xjzhicheng.com)
 * Date: 2016-11-15
 * Describe: PLEASE TO FIXME...
 */
public class SlxyLayout extends FrameLayout implements MaterialStateListener {

    ImageView mImageView;
    AnimationDrawable mAnimationDrawable;

    public SlxyLayout(Context context) {
        this(context, null);
    }

    public SlxyLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlxyLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mImageView = new ImageView(getContext());
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ScreenUtil.dip2px(getContext(), 120),
                ScreenUtil.dip2px(getContext(), 80));
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        mImageView.setLayoutParams(layoutParams);
        mImageView.setImageResource(R.drawable.refresh_anim_list);
        mAnimationDrawable = (AnimationDrawable) mImageView.getDrawable();
        addView(mImageView);
    }


    /**
     * 开启转圈圈
     */
    public void startLoopAnim() {
        if (mAnimationDrawable == null) {
            mAnimationDrawable = (AnimationDrawable) mImageView.getDrawable();
            mAnimationDrawable.setOneShot(false);
        }
        mAnimationDrawable.start();
    }

    /**
     * 停止动画
     */
    public void cancelSunLineAnim() {
        if (mAnimationDrawable != null) {
            mAnimationDrawable.stop();
        }
    }

    @Override
    public void onComlete(InterimLayout materialRefreshLayout) {
        cancelSunLineAnim();
        ViewCompat.setScaleX(this, 0);
        ViewCompat.setScaleY(this, 0);
    }

    @Override
    public void onBegin(InterimLayout materialRefreshLayout) {
        ViewCompat.setScaleX(this, 0.001f);
        ViewCompat.setScaleY(this, 0.001f);
    }

    @Override
    public void onPull(InterimLayout materialRefreshLayout, float fraction) {
        float a = Util.limitValue(1, fraction);
        ViewCompat.setScaleX(this, a);
        ViewCompat.setScaleY(this, a);
        ViewCompat.setAlpha(this, a);
    }

    @Override
    public void onRelease(InterimLayout materialRefreshLayout, float fraction) {

    }

    @Override
    public void onRefreshing(InterimLayout materialRefreshLayout) {
        startLoopAnim();
    }
}
